import {getUserFromCache} from '@/helper/utils'

const perm = {}

let permissions = []
let menus = []
const EMPTY_USER = {
  perms: [],
  menus: []
}

// 加载菜单和权限
const loadMenuAndPerm = function () {
  const userInfo = getUserFromCache() || EMPTY_USER
  permissions = userInfo.perms
  menus = userInfo.menus
  // 后端返回空的时候是{}
  if(Object.prototype.toString.call(menus) !== '[object Array]') {
    menus = []
  }
}

const findMenu = function (menuCode) {
  loadMenuAndPerm()
  return menus.find(n => n.menuCode === menuCode)
}

perm.install = function (Vue) {
  /**
   * <el-button v-perm:权限代码>修改</el-button>
   */
  Vue.directive('perm', {
    inserted(el, binding, vNode) {
      loadMenuAndPerm()
      const {arg, value} = binding
      const perm = value || arg
      if(perm === '' || typeof perm === 'undefined') {
        return
      }
      // 没有权限-直接删除
      if (!permissions.includes(perm)) {
        el.parentNode.removeChild(el)
      }
    }
  })

  /**
   * <el-button v-menu:menuCode>修改</el-button>
   */
  Vue.directive('menu', {
    inserted(el, binding, vNode) {
      const {arg, value} = binding
      const menu = value || arg
      if (!findMenu(menu)) {
        el.parentNode.removeChild(el)
      }
    }
  })

  Vue.prototype.$hasPerm = (perm) => {
    loadMenuAndPerm()
    if(!perm) return true
    return permissions.includes(perm)
  }

  Vue.prototype.$hasMenu = (menu) => !!findMenu(menu)

}

export default perm
